package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.RemoteDeleteCartCheckedList;
import com.spzx.cart.api.RemoteUpdateCartPrice;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.HttpStatus;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.form.OrderForm;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteGetSkuPriceList;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuPriceVo;
import com.spzx.product.api.vo.SkuLockVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author lynn
 * @since 2025-03-18
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private RemoteCartService remoteCartService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteDeleteCartCheckedList remoteDeleteCartCheckedList;

    @Autowired
    private RemoteGetSkuPriceList remoteGetSkuPriceList;

    @Autowired
    private RemoteUpdateCartPrice remoteUpdateCartPrice;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteSkuStockService remoteSkuStockService;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 订单结算
     *
     * @return 订单结算信息
     */
    @Override
    public TradeVo orderTradeData() {

        TradeVo tradeVo = new TradeVo();

        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        //远程调用失败
        if (R.FAIL == cartCheckedListResult.getCode()) {
            throw new ServiceException("远程调用失败");
        }
        List<CartInfo> cartCheckedList = cartCheckedListResult.getData();

        //判断购物车列表是否为空
        if (CollectionUtils.isEmpty(cartCheckedList)) {
            throw new ServiceException("购物车没有选中任何商品");
        }

        List<OrderItem> orderItemList = cartCheckedList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();

            orderItem.setThumbImg(cartInfo.getThumbImg());
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setSkuPrice(cartInfo.getSkuPrice());
            return orderItem;
        }).toList();

        tradeVo.setOrderItemList(orderItemList); //远程调用购物车服务获取购物车列表

        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount
                    .add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        tradeVo.setTotalAmount(totalAmount); //总金额

        tradeVo.setTradeNo(generateTradeNo()); //生成订单号
        tradeVo.setIsBuy(false); //从购物车点击"结算"

        return tradeVo;
    }

    /**
     * 生成订单号并放入redis
     *
     * @return
     */
    private String generateTradeNo() {

        Long userId = SecurityContextHolder.getUserId();

        //1.构建流水号key
        String userTradeKey = "user:tradeNo:" + userId;

        //2.流水号value
        String tradeNo = UUID.randomUUID().toString().replace("-", "");

        //3.将流水号放入redis 过期时间五分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);

        return tradeNo;
    }

    /**
     * 验证页面提交流水号是否有效
     *
     * @param tradeNo
     * @return
     */
    private Boolean checkTradeNo(String tradeNo) {
        Long userId = SecurityContextHolder.getUserId();
        String userTradeKey = "user:tradeNo:" + userId;
        //从redis中获取流水号
        String redisTradeNo = (String) redisTemplate.opsForValue().get(userTradeKey);
        //如果流水号不一致，则返回false
        return tradeNo.equals(redisTradeNo);
    }

    /**
     * 删除流水号
     */
    private void deleteTradeNo() {
        Long userId = SecurityContextHolder.getUserId();
        String userTradeKey = "user:tradeNo:" + userId;
        redisTemplate.delete(userTradeKey);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {

        //获取用户id
        Long userId = SecurityUtils.getUserId();
        //构建流水号key
        String userTradeKey = "user:tradeNo:" + userId;

        //1 防止订单重复提交&防止页面停留超时
        //在展示订单列表时就设置了TradeNo 存到redis中了
        //如果订单号在redis中存在，则说明是第一次提交。需要删除删除redis中的流水号
        //多次点击的话 因为第一次点击提交之后就已经将redis中的流水号删除了，所以第二次点击就会显示订单已提交
/*        if (checkTradeNo(orderForm.getTradeNo())) {
            deleteTradeNo();
        } else {
            throw new ServiceException("订单已提交，请勿重复提交");
        }*/

        /**
         * 如果redis中的流水号过期了，我第一次点击结算但是还没有点提交订单
         * 那么也会显示 “订单已提交” 这不符合逻辑 所以在第一次提交之后 需要修改redis中对应的流水号 以区分删除流水号
         * 另外 如果在多并发的情况下 判断是否被删除 可能多次判断均为第一次提交 不满足原子性
         * 结合以上 以下为优化方式 使用lua脚本
         */

        // 将键的值更为 processed  表示已处理
        // return 1 表示处理成功
        // return -1  键存在但值不匹配，表示重复提交
        // return 0   键不存在，订单过期
        String scriptText = """
               if redis.call('get', KEYS[1]) == ARGV[1] then
                       redis.call('set', KEYS[1], 'processed', 'ex', ARGV[2])
                       return 1
               else
                   	if redis.call('exists', KEYS[1]) == 1 then
                           return -1
                   else
                       	return 0
                       end
                   end
                """;
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        Long flag = (Long)redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), orderForm.getTradeNo(), 3);
        if (flag == 0) {
            throw new ServiceException("操作超时，请退回重试");
        }
        if(flag == -1){
            throw new ServiceException("请勿重复提交订单", HttpStatus.SUBMIT_REPEATE);
        }

        //2 判断价格是否改变
        // 2.1 获取购买时商品价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();

        //2.2获取最新价格列表
        R<List<SkuPriceVo>> skuPriceListResult = remoteGetSkuPriceList.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPriceVo> skuPriceVoList = skuPriceListResult.getData();

        // 2.3 并判断价格是否变更

        StringBuilder priceCheckResult = new StringBuilder();
        Map<Long, BigDecimal> skuPriceVoMap = skuPriceVoList.stream().collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        for (OrderItem orderItem : orderItemList) {
            BigDecimal skuPrice = skuPriceVoMap.get(orderItem.getSkuId());
            // 2.4 如果有变更 将信息添加到字符串
            if (skuPrice.compareTo(orderItem.getSkuPrice()) != 0) {
                priceCheckResult.append(orderItem.getSkuName()).append("\n");
            }
        }

        //如果价格真发生变化
        if (StringUtils.isNotBlank(priceCheckResult.toString())) {
            if (!orderForm.getIsBuy()) { //如果从购物车点击结算，则更新购物车商品列表价格
                //更新redis中购物车商品列表价格
                R<Boolean> updateCartPriceResult = remoteUpdateCartPrice.updateCartPrice(SecurityConstants.INNER);
                if (updateCartPriceResult.getCode() == R.FAIL) {
                    throw new ServiceException("更新购物车商品价格失败" + updateCartPriceResult.getMsg());
                }
            }
            throw new ServiceException("价格发生变化,请重新下单：" + priceCheckResult);
        }


        //3 校验库存并锁定库存
        List<SkuLockVo> skuLockVoList = new ArrayList<>();
        for (OrderItem orderItem : orderItemList) {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            skuLockVo.setSkuName(orderItem.getSkuName());
            skuLockVoList.add(skuLockVo);
        }
        R<String> checkAndLockResult = remoteSkuStockService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);
        if(R.FAIL == checkAndLockResult.getCode()){
            throw new ServiceException("远程调用失败：" + checkAndLockResult.getMsg());
        }
        String resultData = checkAndLockResult.getData();
        if (StringUtils.isNotBlank(resultData)){
            throw new ServiceException(resultData);
        }

        //4 下单
        Long orderId = null;
        try {
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //下单失败时 解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK,orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }

        //5 删除购物车选中商品
        if (!orderForm.getIsBuy()) { //如果从购物车点击结算，则删除购物车选中商品
            remoteDeleteCartCheckedList.deleteCartCheckedList(userId, SecurityConstants.INNER);
        }

        return orderId;
    }

    @Override
    public TradeVo orderTradeBuyData(Long skuId) {
        //在数据库中查询商品信息 封装到TradeVo
        TradeVo tradeVo = new TradeVo();
        R<ProductSkuVo> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuResult.getCode()) {
            throw new ServiceException("远程调用失败" + productSkuResult.getMsg());
        }
        ProductSkuVo productSkuVo = productSkuResult.getData();

        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSkuVo.getSkuName());
        orderItem.setSkuPrice(productSkuVo.getSalePrice());
        orderItem.setSkuNum(1);
        orderItem.setThumbImg(productSkuVo.getThumbImg());

        tradeVo.setTotalAmount(productSkuVo.getSalePrice());
        tradeVo.setOrderItemList(Collections.singletonList(orderItem));
        tradeVo.setIsBuy(true);
        tradeVo.setTradeNo(generateTradeNo());
        return tradeVo;
    }

    /**
     * 根据订单id查询订单信息
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderInfo selectOrderInfoById(Long orderId) {
        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper);

        OrderInfo orderInfo = baseMapper.selectById(orderId);
        orderInfo.setOrderItemList(orderItemList);

        return orderInfo;
    }

    /**
     * 根据用户id和订单状态查询订单列表
     *
     * @param orderStatus
     * @return
     */
    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        Long userId = SecurityContextHolder.getUserId();

        List<OrderInfo> orderInfoList = orderInfoMapper.selectList(
                new LambdaQueryWrapper<OrderInfo>()
                        .eq(OrderInfo::getUserId, userId)
                        .eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus)
                        .orderByDesc(OrderInfo::getCreateTime));

/*        //设置每个OrderInfo 中的OrderItemList
        orderInfoList = orderInfoList.stream().map(orderInfo -> {
            orderInfo.setOrderItemList(orderItemMapper.selectList(
                    new LambdaQueryWrapper<OrderItem>()
                            .eq(OrderItem::getOrderId, orderInfo.getId())
            ));
            return orderInfo;
        }).toList();
        return orderInfoList;*/


        // 上述方法优化：
        // 查询一次数据库 再根据orderId分配orderItemList
        if (orderInfoList.isEmpty()) {
            return orderInfoList;
        }
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>()
                .in(OrderItem::getOrderId, orderInfoList.stream().map(OrderInfo::getId).toList()));
        orderInfoList.forEach(orderInfo -> {
            orderInfo.setOrderItemList(orderItemList.stream()
                    .filter(orderItem -> orderItem.getOrderId().equals(orderInfo.getId()))
                    .collect(Collectors.toList()));
        });
        return orderInfoList;

    }

    /**
     * 取消订单
     *
     * @param orderId
     */
    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        if (orderInfo != null && orderInfo.getOrderStatus().intValue() == 0) {//待付款
            String username = SecurityUtils.getUsername();

            orderInfo.setOrderStatus(-1);//已取消
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            baseMapper.updateById(orderInfo);
            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("用户取消订单");
            orderLog.setOperateUser(username);
            orderLog.setCreateBy(username);
            orderLog.setUpdateBy(username);
            orderLogMapper.insert(orderLog);
            //发送MQ消息通知商品系统解锁库存：
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }

    /**
     * 根据订单号获取订单信息
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        //订单
        OrderInfo orderInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo)
        );
        //订单详情
        List<OrderItem> orderItemList = orderItemMapper.selectList(
                new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId())
        );
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    /**
     * 支付成功后更新订单状态
     * @param orderNo
     */
    @Override
    public void processPaySuccess(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));

        //幂等性判断
        if(orderInfo.getOrderStatus() == 1){
            return;
        }
        orderInfo.setOrderStatus(1);
        orderInfo.setPaymentTime(new Date());
        orderInfoMapper.updateById(orderInfo);
    }

    /**
     * 保存订单数据
     *
     * @param orderForm
     * @return 订单id
     */
    private Long saveOrder(OrderForm orderForm) {

        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();

        //订单总金额
        BigDecimal totalAmount = this.getTotalAmount(orderForm);

        //1.保存oderInfo
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(username);
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        orderInfo.setOriginalTotalAmount(totalAmount); //原价金额
        orderInfo.setCouponAmount(BigDecimal.ZERO); //优惠券优惠金额
        orderInfo.setRemark(orderForm.getRemark());

        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER);
        if (R.FAIL == userAddressResult.getCode()) {
            throw new ServiceException(userAddressResult.getMsg());
        }
        UserAddress userAddress = userAddressResult.getData();
        if (userAddress == null) {
            throw new ServiceException("订单未设置地址!");
        }

        //保存用户地址
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getAddress());

        orderInfo.setCreateBy(username);
        orderInfo.setUpdateBy(username);
        orderInfo.setOrderStatus(0); //待付款


        orderInfoMapper.insert(orderInfo);

        //获取插入后生成的订单id
        Long orderId = orderInfo.getId();

        //2.保存orderItem
        orderForm.getOrderItemList().forEach(orderItem -> {
            orderItem.setOrderId(orderId);
            orderItem.setCreateBy(username);
            orderItem.setUpdateBy(username);
            orderItemMapper.insert(orderItem);
        });

        //3.保存orderLog
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setProcessStatus(0); //待付款
        orderLog.setOperateUser(username);
        orderLog.setNote("提交订单");
        orderLog.setCreateBy(username);
        orderLog.setUpdateBy(username);
        orderLogMapper.insert(orderLog);


        return orderId;
    }


    /**
     * 根据订单表单获取订单总金额
     *
     * @param orderForm
     * @return
     */
    private BigDecimal getTotalAmount(OrderForm orderForm) {
        return orderForm.getOrderItemList().stream().map(
                orderItem -> orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum()))
        ).reduce(BigDecimal.ZERO, BigDecimal::add);
    }


}
